<template>
  <div class="app-container ">
    <div class="flex cursor">
      <div class="custom-title margin-right-lg " :class="tag==index?'active':''" v-for="(item,index) in carTypeList"
        @click="bindCarRadio(item.label,item.value,index)">{{item.label}}</div>
    </div>
    <el-form :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="日期" prop="monthYear">
        <el-date-picker style="margin-right:8px" v-model="dateSection" type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
          @change="bindChangeAllDate" />
      </el-form-item>
      <el-form-item label="稽核员" prop="auditor">
        <el-input v-model="queryParams.auditor" placeholder="请输入稽核员姓名" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd()" v-hasPermi="['audit:cAuditData:add']" v-if="tag==0">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="[tag==0?'audit:cAuditData:export':'audit:cAuditData:monExport']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table :data="tableData" v-loading="loading" show-overflow-tooltip style="width: 100%;" :header-cell-style="{ 'text-align': 'center '}" >
      <template v-for="(item,index) in goOutContent">
        <el-table-column :label="item.title" v-if="item.children" align="center">
          <template v-for="(element) in item.children">
            <el-table-column :prop="element.prop" :label="element.title" align="center" v-if="!element.children" />
            <el-table-column :label="element.title" v-else align="center">
              <template v-for="(option) in element.children">
                <el-table-column :prop="option.prop" align="center" :label="option.title">
                  <template #default="scope">
                    <span v-if="option.render">
                      {{option.render(scope.row[option.prop],scope.row)}}</span>
                    <span v-else>{{ scope.row[option.prop]=='null'?'-':scope.row[option.prop] }}</span>
                  </template>
                </el-table-column>
              </template>
            </el-table-column>
          </template>
        </el-table-column>
        <el-table-column :prop="item.prop" :label="item.title" align="center" :width="item.width" :fixed="item.fixed" v-else>
          <template #default="scope">
            <span v-if="item.render">
              {{item.render(scope.row[item.prop],scope.row)}}</span>
            <span v-else>{{ scope.row[item.prop]=='null'?'-':scope.row[item.prop] }}</span>
          </template>
        </el-table-column>
      </template>
      <el-table-column prop="index" label="操作" width="260" fixed="right" v-if="tag==0">
        <template #default="scope">
          <el-button link icon="Edit" size="small" v-hasPermi="['audit:cAuditData:edit']" type="primary" @click.prevent="handleUpdate(scope.row)">
            修改
          </el-button>
          <el-button link icon="View" size="small" type="primary" @click.prevent="handleUpdate(scope.row,1)">
            查看详情
          </el-button>
          <el-popconfirm title="确认删除本条数据?" v-hasPermi="['audit:cAuditData:remove']" @confirm="handleDelete(scope.row)">
            <template #reference>
              <el-button link icon="Delete" type="primary" size="small">
                删除
              </el-button>
            </template>
          </el-popconfirm>

        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改流程分类对话框 -->
    <el-dialog :title="title" v-model="open" width="1200px" append-to-body :close-on-click-modal="false">

      <el-form :model="rowDetails" ref="cAuditDataRef" :inline="true">
        <el-form-item label="日期" prop="auditDate">
          <el-date-picker v-model="rowDetails.auditDate"    type="date" value-format="YYYY-MM-DD"  @change="bindChangeDate" />
        </el-form-item>
        <el-form-item label="稽核员" prop="auditorId">

          <el-select v-model="rowDetails.auditorId" placeholder="请选择" clearable style="width: 240px">
            <el-option v-for="dict in auditorList" :key="dict.userId" :label="dict.userName" :value="dict.userId" />
          </el-select>
        </el-form-item>
      </el-form>
      <div v-if="site">您负责的站点：{{site}}</div>
      <div class="table-none">
        <div class="title" ><span class="text-large font-600 mr-3"> 稽核分析系统 </span></div>
        <el-table :data="dialogTableData" style="width: 100%" :span-method="arraySpanMethod" >
          <el-table-column prop="type" label="类型" align="center" />
          <el-table-column prop="name" label="稽核项" align="center" />
          <el-table-column prop="num" label="总量" align="center">
            <template #default="scope">
              <el-input-number :controls="false" v-model="rowDetails[scope.row.prop]" :placeholder="scope.$index>2?'-':'请输入'" :disabled="scope.$index>2"
                @input="bindChangeRoutine($event,scope.row.prop,scope.$index)" class="inputDeep" input-style="textAlign:center" />
            </template>
          </el-table-column>
          <el-table-column prop="num2" label="处理量" align="center">
            <template #default="scope">
              <el-input-number :controls="false" v-model="rowDetails[scope.row.propHand]" placeholder="请输入"
                @input="bindChangeRoutine($event,scope.row.propHand,scope.$index)" class="inputDeep" input-style="textAlign:center" />
            </template>
          </el-table-column>
        </el-table>

        <div class="title"><span class="text-large font-600 mr-3"> 自行发起黑名单 </span></div>
        <el-descriptions border style="width: 800px">
          <el-descriptions-item label="省级">
            <el-input-number :controls="false" v-model="rowDetails.zxfqBlackPro" placeholder="请输入" @input="bindChangeRoutine($event,'zxfqBlackPro')"
              class="inputDeep" input-style="textAlign:center" />
          </el-descriptions-item>
          <el-descriptions-item label="部级">
            <el-input-number :controls="false" v-model="rowDetails.zxfqBlackMin" placeholder="请输入" @input="bindChangeRoutine($event,'zxfqBlackMin')"
              class="inputDeep" input-style="textAlign:center" />
          </el-descriptions-item>
        </el-descriptions>

        <div class="title" ><span class="text-large font-600 mr-3"> 部级稽核业务平台 </span></div>
        <el-descriptions border style="width: 400px">
          <el-descriptions-item label="工单处理">
            <el-input-number :controls="false" v-model="rowDetails.bjptDeal" placeholder="请输入" @input="bindChangeRoutine($event,'bjptDeal')" class="inputDeep"
              input-style="textAlign:center" />
          </el-descriptions-item>
        </el-descriptions>

        <div class="title"><span class="text-large font-600 mr-3"> 对账业务平台 </span></div>
        <el-descriptions border style="width:400px" >
          <el-descriptions-item label="工单审核">
            <el-input-number :controls="false" v-model="rowDetails.dzptCheck" placeholder="请输入" @input="bindChangeRoutine($event,'dzptCheck')" class="inputDeep"
              input-style="textAlign:center" />
          </el-descriptions-item>
        </el-descriptions>

        <div class="title"><span class="text-large font-600 mr-3"> 其他 </span></div>
        <el-input :controls="false" v-model="rowDetails.others" placeholder="请输入" @input="bindChangeRoutine($event,'others')" class="inputDeep" type="textarea"
          rows="5" />

      </div>

      <template #footer v-if="!isView">
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm"> 保存</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import moment from 'moment'
import { deptTreeSelect } from "@/api/system/user";
import { listCAuditData, getCAuditData, delCAuditData, addCAuditData, updateCAuditData, getDutyInfo, getMonAuditList } from "@/api/charge/cAuditData";
import { listCAuditor } from "@/api/charge/cAuditor";

import config from "./config"
import useUserStore from '@/store/modules/user'

const { proxy } = getCurrentInstance();
const userStore = useUserStore()
const goOutContent = ref(config.goOutContent1)
const tag = ref(0)
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const deptOptions = ref([])
const dateSection = ref([])
const auditorList=ref([])
const open = ref(false)
const form = ref({})
const userName = ref()
const isView = ref(false)
const queryDialogParams = ref({})
const userId = ref()
const site = ref()
const dutyPlat = ref()
const dialogTableData = ref([{ type: '稽核分析系统', name: "特情稽核", prop: 'specialTotal', propHand: "specialCount" }, { type: '稽核分析系统', name: "内部稽核", prop: 'innerTotal', propHand: "innerCount" }, { type: '稽核分析系统', name: "逃费稽核", prop: 'fleeTotal', propHand: "fleeCount" },
{ type: '工单发起与审核', name: "审核工单", prop: '', propHand: "gdfqCheckOrder" }, { type: '工单发起与审核', name: "省内黑名单", prop: '', propHand: "gdfqProBlack" },
{ type: '工单发起与审核', name: "外部稽核", prop: '', propHand: "gdfqOutAudit" }])

const rowDetails = ref({})
const title = ref('稽核工单处理上报')
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
})
const carTypeList = ref([
  { label: '集中稽核工单处理日报表', value: "0", interface: 'Cyxxhz' },
  { label: '集中稽核工单处理月报表', value: "1", interface: 'Txfzszxjhyb' }
])
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
};
/** 查询集中稽核列表 */
function getList() {
  loading.value = true;
  listCAuditData(queryParams.value).then(response => {
    tableData.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
function getMonList() {
  loading.value = true;
  getMonAuditList(queryParams.value).then(response => {
    tableData.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
const bindChangeRoutine = (val, name) => {
  rowDetails.value[name] = val;
}
function handleQuery() {
  if(tag.value==0){
    getList()
  }else{
    getMonList()
  }
 
};
const bindChangeAllDate = (val) => {
  if (!val) { dateSection.value = []; queryParams.value.startDate = ''; queryParams.value.endDate = ''; return }
  dateSection.value = [moment(val[0]).format("YYYY-MM-DD"), moment(val[1]).format("YYYY-MM-DD")]
  queryParams.value.startDate = dateSection.value[0];
  queryParams.value.endDate = dateSection.value[1];
}
const bindCarRadio = (name, val, index) => {
  goOutContent.value = config[`goOutContent${(Number(index) + 1)}`];
  tableData.value = [];
  tag.value = val;
  if (tag.value == 1) {
    let startDateMonth = moment().startOf('month').format('YYYY-MM-DD');
    let endDateMonth = moment().endOf('month').format('YYYY-MM-DD')
    dateSection.value = [startDateMonth, endDateMonth]
    queryParams.value.startDate = startDateMonth;
    queryParams.value.endDate = endDateMonth;
    getMonList()
  } else {
    let startDate = moment().format("YYYY-MM-DD");
    dateSection.value = [startDate, startDate]
    queryParams.value.startDate = startDate;
    queryParams.value.endDate = startDate;
    getList()
  }


}

// 表格
const arraySpanMethod = ({
  row,
  column,
  rowIndex,
  columnIndex,
}) => {
  if (columnIndex === 0) {
    const currentValue = row["type"];
    // 获取上一行相同列的值
    const preRow = dialogTableData.value[rowIndex - 1];
    const preValue = preRow ? preRow["type"] : null;
    if (currentValue === preValue) {
      return { rowspan: 0, colspan: 0 };
    } else {
      // 否则计算当前单元格应该跨越多少行
      let rowspan = 1;
      for (let i = rowIndex + 1; i < dialogTableData.value.length; i++) {
        const nextRow = dialogTableData.value[i];
        const nextValue = nextRow["type"];
        if (nextValue === currentValue) {
          rowspan++;
        } else {
          break;
        }
      }
      return { rowspan, colspan: 1 };
    }
  }

}

function reset() {
  isView.value = false;
  // userId: userId.value,
  // rowDetails.value = { userName: userName.value,  auditDate: moment().format("YYYY-MM-DD") };
  // proxy.resetForm("cAuditDataRef");
}
/** 新增按钮操作 */
function handleAdd(date) {
  reset();
  rowDetails.value={userName: userName.value,  auditDate: date?moment(date).format("YYYY-MM-DD"):moment().format("YYYY-MM-DD") }
  isView.value = false;
  open.value = true;
  title.value = "添加集中稽核数据记录";
}

/** 修改按钮操作 */
function handleUpdate(row, type) {
  reset();
  const _id = row.id || ids.value
  getCAuditData(_id).then(response => {
    rowDetails.value = response.data;
    if (type == 1) { isView.value = true } else {
      isView.value = false
    }
    open.value = true;
    title.value = "修改集中稽核数据记录";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["cAuditDataRef"].validate(valid => {
    if (valid) {
      if (Object.keys(rowDetails.value).length <= 3) {
        proxy.$modal.msgError("您未填充数据");
        return;
      }
      if (rowDetails.value.id != null) {
        updateCAuditData(rowDetails.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCAuditData(rowDetails.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除集中稽核数据记录编号为"' + _ids + '"的数据项？').then(function () {
    return delCAuditData(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  let url = tag.value == 0 ? 'audit/cAuditData/export' : 'audit/cAuditData/monExport'
  let name = tag.value == 0 ? '集中稽核工单处理日报表' : '集中稽核工单处理月报表'
  proxy.download(url, {
    ...queryParams.value
  }, `${name}_${new Date().getTime()}.xlsx`)
}
const cancel = () => {
  open.value = false;
}
const bindChangeDate = (val) => {
  rowDetails.value.auditDate = moment(val).format("YYYY-MM-DD")


  handleAdd(moment(val).format("YYYY-MM-DD"))
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  let startDate = moment().format("YYYY-MM-DD");
  dateSection.value = [startDate, startDate]
  queryParams.value.startDate = startDate;
  queryParams.value.endDate = startDate;
  handleQuery();
}

const init = () => {
  let startDate = moment().format("YYYY-MM-DD");
  dateSection.value = [startDate, startDate]
  queryParams.value.startDate = startDate;
  queryParams.value.endDate = startDate;
  rowDetails.value.auditDate = startDate;


}
const getInfo = (auditorId) => {
  getDutyInfo({ auditorId }).then(res => {
    site.value = '';

    if (res.code == 200 && res.data && res.data.tbCentreAuditorDeptList) {
      dutyPlat.value = res.data.dutyPlat
      res.data.tbCentreAuditorDeptList.forEach((element, index) => {
        site.value += element.dutyDeptName + ((index == (res.data.tbCentreAuditorDeptList.length - 1)) ? '' : ',')
      });
    }
  })
}
const getUserInfo = () => {
  userStore.getInfo().then(res => {
    if (res.code == 200) {
      // deptId.value = res.user.dept.deptId;
      userId.value = res.user.userId;
      userName.value = res.user.userName;
      rowDetails.value.userName = userName.value;
      rowDetails.value.userId = userId.value;
      // queryParams.value.auditorId = userId.value;
      getList()
      getInfo(userId.value)
    }

  })
}
const getPreonList=()=>{
  listCAuditor({pageNum: 1,pageSize: 100}).then(res => {
    if (res.code == 200) {
      auditorList.value=res.rows

    }

})
}
getPreonList()

getUserInfo()
getDeptTree()
init()
</script>
<style scoped>
.flex {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.flex .label {
  color: #333;
  font-size: 14px;
}
.margin-right-lg {
  margin-right: 32px;
}
.margin-right {
  margin-right: 8px;
}
.align-center {
  display: flex;
  align-items: center;
}
.margin-top {
  margin-top: 20px;
}
/deep/ .input-height .el-input__wrapper {
  height: 32px;
}
/deep/ .input-height .el-date-editor.el-input {
  height: 32px;
}
.title {
  position: relative;
  font-size: 18px;
  font-weight: 800;
  margin: 20px 0;
}
.title::before {
  content: "";
  display: block;
  position: absolute;
  width: 100px;
  height: 6px;
  bottom: 0;
  background: linear-gradient(270deg, rgba(248, 115, 115, 0) 0%, #2252d6 100%);
  border-radius: 3px;
  opacity: 0.7;
}
.inputDeep >>> .el-input__wrapper {
  width: 100%;
  height: 30px;
  line-height: 30px;
  box-shadow: none !important;
  /* border-bottom: 1px solid #eee; */
}

.active {
  position: relative;
}
.active::before {
  content: "";
  display: block;
  width: 50px;
  height: 2px;
  border-radius: 2px;
  background: var(--el-color-primary);
  position: absolute;
  bottom: 3px;
  left: 50%;
  transform: translateX(-50%);
}
</style>